package com.gitee.xjt2016.modules.quiver;

import cn.hutool.core.io.FileUtil;
import com.gitee.xjt2016.Article;
import lombok.Data;
import lombok.NonNull;
import org.nutz.json.Json;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Qvnotebook.
 * 文章分类，目录
 *
 * @author xiongjinteng@raycloud.com
 */
@Data
public class Qvnotebook extends Quiver {

    private QvnotebookMeta qvnotebookMeta;

    private List<Qvnote> qvnoteList;

    private String path;

    public Qvnotebook(File qvnotebookFile) {
        this.path = qvnotebookFile.getAbsolutePath();
        String qvnotebookMetaJsonPath = this.getPath() + "/meta.json";
        QvnotebookMeta qvnotebookMeta = Json.fromJsonFile(QvnotebookMeta.class, new File(qvnotebookMetaJsonPath));
        this.setQvnotebookMeta(qvnotebookMeta);
        this.setName(qvnotebookMeta.getName());
        this.setUuid(qvnotebookMeta.getUuid());
        this.setQvnoteList(getQvnoteList(qvnotebookFile));
    }

    private static List<Qvnote> getQvnoteList(@NonNull File qvnotebookFile) {
        List<Qvnote> qvnoteList = new ArrayList<>();
        File[] files = qvnotebookFile.listFiles();
        if (files == null || files.length <= 0) {
            return qvnoteList;
        }

        for (File qvnoteFile : files) {
            if (qvnoteFile.isDirectory() && qvnoteFile.getName().endsWith(".qvnote")) {
                String qvnoteFilePath = qvnoteFile.getAbsolutePath();
                String qvnoteMetaJsonPath = qvnoteFilePath + "/meta.json";
                String contentJsonPath = qvnoteFilePath + "/content.json";
                String resourcesPath = qvnoteFilePath + "/resources/";

                String contentJson = FileUtil.readUtf8String(new File(contentJsonPath));
                String qvnoteMetaJson = FileUtil.readUtf8String(new File(qvnoteMetaJsonPath));

                Qvnote qvnote = new Qvnote();
                qvnote.setPath(qvnoteFilePath);
                qvnote.setArticle(Json.fromJson(Article.class, contentJson));
                qvnote.setQvnoteMeta(Json.fromJson(QvnoteMeta.class, qvnoteMetaJson));
                qvnote.setResourcesPath(resourcesPath);

                qvnoteList.add(qvnote);
            }
        }
        return qvnoteList;
    }
}
